

use anyhow::Result;
use tauri::menu::{CheckMenuItem, Menu, MenuItem, SubmenuBuilder};
use tauri::tray::{MouseButton,TrayIconBuilder, TrayIconEvent};
use tauri::webview::PageLoadPayload;
use tauri::{App, AppHandle, Manager, Runtime, Webview, WebviewWindowBuilder, Window, WindowEvent};
use tauri::{Builder,Wry};
use tauri_plugin_log::log::info;
use tauri_plugin_log::{Target, TargetKind};
use tracing::log::LevelFilter;
mod commands;
use commands::greet;
use commands::get_app_dir;

use crate::utils::log_dir;
pub mod utils;

const APP_NAME: &str = "Hn";


pub fn app() -> Result<Builder<Wry>> {
    let builder = tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .plugin(logger().build())
        .invoke_handler(tauri::generate_handler![
            greet,
            get_app_dir
            ])
            .setup(setup)
            .on_page_load(page_load_handler)
            .on_window_event(window_event_handler);
    Ok(builder)
}

fn page_load_handler(webview: &Webview,_payload: &PageLoadPayload<'_>) {
    info!("Page loaded: {:?}",webview.label());
}

fn window_event_handler(window: &Window, event: &WindowEvent) {
    info!("Window event: {:?} on {:?}", event, window.label());

    if let WindowEvent::CloseRequested { api, .. } = event {
        if window.label() == "main" {
            api.prevent_close();
            window.hide().unwrap()
        }
    }
}

fn setup(app: &mut App) -> Result<(),Box<dyn std::error::Error>> {
    info!("Setting up app");

    let handle = app.handle();
    #[cfg(desktop)]
    {


        handle.plugin(tauri_plugin_window_state::Builder::default().build())?;
    }
    setup_menu(handle)?;
    let mut builder = WebviewWindowBuilder::new(app,
    "main",tauri::WebviewUrl::default());

    #[cfg(desktop)]
    {

        builder = builder
        .title("Hacker News")
        .user_agent(&format!("Hn app - {}",std::env::consts::OS))
        .inner_size(1200., 800.)
        .min_inner_size(800.,600.)
        .content_protected(true)
        .resizable(true)
    }
    let webview = builder.build()?;

    #[cfg(debug_assertions)]
    webview.open_devtools();
    Ok(())
}

fn logger() -> tauri_plugin_log::Builder {
    tauri_plugin_log::Builder::default()
        .targets([
            Target::new(TargetKind::Webview),
            Target::new(TargetKind::Folder { path: log_dir(), file_name: Some("app".to_string()) }),
            Target::new(TargetKind::Stdout),
        ]).level(LevelFilter::Info)

    }

fn setup_menu<R: Runtime>(app: &AppHandle<R>) ->Result<(), tauri::Error> {
    let icon = app.default_window_icon().unwrap().clone();
    //create submenus and menus here
    //add menu to tray
    //add menu to window
    let file_menu = SubmenuBuilder::with_id(app, "file", "File")
    .item(&MenuItem::with_id(app,"Open","open",true,Some("CmdOrCtrl+o"))?)
    .item(&MenuItem::with_id(app,"Save","save",true,Some("CmdOrCtrl+s"))?)
    .item(&MenuItem::with_id(app,"Save As","save_as",true,Some("CmdOrCtrl+Shift+s"))?)
    .separator()
    .quit()
    .build()?;
    let edit_menu = SubmenuBuilder::with_id(app, "edit", "Edit")
    .item(&MenuItem::with_id(app,"Process","process",true,Some("CmdOrCtrl+p"))?)
    .separator()
    .undo()
    .redo()
    .separator()
    .cut()
    .copy()
    .paste()
    .separator()
    .select_all()
    .item(&CheckMenuItem::new(app, "Check Me",true,true,None::<&str>)?)
    .build()?;

    let tray_menu = SubmenuBuilder::with_id(app, "tray", "Tray")
    .item(&MenuItem::with_id(app,"Open","open",true,None::<&str>)?)
    .item(&MenuItem::with_id(app,"Hide","hide",true,None::<&str>)?)
    .separator()
    .quit()
    .build()?;

    TrayIconBuilder::with_id(format!("{}-tray",APP_NAME))
    .tooltip("Hacker News")
    .icon(icon)
    .menu(&tray_menu)
    .show_menu_on_left_click(true)
    .on_tray_icon_event(|tray,event|{
        info!("Tray icon event: {:?} on {:?}", event, tray.id());
        if let TrayIconEvent::Click {
            button: MouseButton::Right,
            ..
        } = event
        {
            open_main(tray.app_handle()).unwrap();
        }
    }).build(app)?;
    
    let menu = Menu::with_items(app,&[&file_menu,&edit_menu])?;

    app.set_menu(menu)?;

    app.on_menu_event(|app,event|{
        info!("Menu event: {:?} on {:?}",event,app);
        match event.id.as_ref() {
            "open" => open_main(app).unwrap(),
            "save" => {}
            "save_as" => {}
            "process" => {}
            "Check Me" => {}
            _ => {}
        }
    });
    Ok(())
  }
fn open_main<R: Runtime>(handle: &AppHandle<R>) ->Result<(),tauri::Error> {
    // handle.get_webview_window("main")
    //     .unwrap().show().unwrap();
    handle.get_webview_window("main")
        .ok_or_else(|| tauri::Error::WindowNotFound)?
        .show()?;
    Ok(())
}

// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
// #[cfg_attr(mobile, tauri::mobile_entry_point)]
// pub fn run() {
//     tauri::Builder::default()
//         .plugin(tauri_plugin_opener::init())
//         .invoke_handler(tauri::generate_handler![greet])
//         .run(tauri::generate_context!())
//         .expect("error while running tauri application");
// }
